package com.example.caoben_back.contoller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.caoben_back.entity.po.Floor;
import com.example.caoben_back.entity.po.User;
import com.example.caoben_back.entity.vo.Result;
import com.example.caoben_back.service.IFloorService;
import com.example.caoben_back.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/floor")
public class FloorController {

    @Autowired
    private IFloorService floorService;
    
    // 发布楼层（回复帖子）
    @PostMapping("/publish")
    public Result<Integer> publishFloor(@RequestBody Floor floor,
                                       HttpServletRequest request) {
        // 从token中解析用户信息
        User user = TokenUtil.getUserFromRequest(request);
        if (user == null) {
            return Result.fail("用户未登录");
        }
        Integer userId = user.getUserId();
        
        floor.setUserId(userId);
        floor.setPublishTime(LocalDateTime.now());
        floorService.save(floor);
        return Result.success(floor.getFloorId());
    }

    // 获取帖子下的楼层列表
    @GetMapping("/list")
    public Result<Map<String, Object>> getPostFloors(@RequestParam Integer postId,
                                                     @RequestParam Integer page,
                                                     @RequestParam Integer size) {
        Page<Floor> floorPage = floorService.page(new Page<>(page, size),
                new QueryWrapper<Floor>().eq("post_id", postId).orderByAsc("floor_id"));
        Map<String, Object> data = new HashMap<>();
        data.put("list", floorPage.getRecords());
        data.put("total", floorPage.getTotal());
        return Result.success(data);
    }

    // 删除楼层
    @DeleteMapping("/delete")
    public Result<Boolean> deleteFloor(@RequestParam Integer floorId) {
        return Result.success(floorService.removeById(floorId));
    }
}